;;; Copyright (C) 2013 Alessio Stalla
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

(defpackage :tag-pool-templating
  (:use :cl :tag-pool :closure-html :css-selectors :doplus)
  (:export #:compile-template #:deftemplate))

(in-package :tag-pool-templating)

(defun compile-template (source arglist)
  "arglist: list of (var selector &optional default-function)"
  (let* ((dom (closure-html:parse source (cxml-dom:make-dom-builder)))
         (arg-map (mapcar (lambda (arg)
                            (let ((placeholder (princ-to-string (uuid:make-v4-uuid)))
                                  (targets (query (cadr arg) dom)))
                              (dolist (to-replace targets)
                                (dom:replace-child
                                 (dom:parent-node to-replace)
                                 (dom:create-text-node dom placeholder)
                                 to-replace))
                              (cons (cons (car arg) (cddr arg)) placeholder)))
                          arglist)))
    (labels ((gen-body (template)
               (dolist (arg-def arg-map)
                 (let* ((arg-name (caar arg-def))
                        (placeholder (cdr arg-def))
                        (pos (search placeholder template)))
                   (when pos
                     (return-from gen-body
                       `(,@(gen-body (subseq template 0 pos))
                         (when ,arg-name
                           (funcall ,arg-name))
                         ,@(gen-body (subseq template (+ pos (length placeholder)))))))))
               `((out ,template))))
      `(lambda (&key ,@(mapcar #'car arg-map))
         ,@(gen-body (dom:map-document (cxml:make-string-sink) dom))))))

(defmacro deftemplate (name source arglist)
  (let ((template-lambda (compile-template source arglist)))
    `(defun ,name ,(cadr template-lambda)
       ,@(cddr template-lambda))))